<template>
  <div
    class="comment-section bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6"
  >
    <!-- 评论标题 -->
    <div class="flex items-center gap-3 mb-6">
      <div
        class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center"
      >
        <svg class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
          <path
            fill-rule="evenodd"
            d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7z"
            clip-rule="evenodd"
          />
        </svg>
      </div>
      <h3 class="text-xl font-semibold text-gray-800 dark:text-white">
        评论 ({{ totalComments }})
      </h3>
    </div>

    <!-- 评论输入框 -->
    <div class="comment-input mb-6">
      <div class="flex items-start gap-3">
        <div
          class="w-10 h-10 bg-gradient-to-br from-green-400 to-blue-500 rounded-full flex items-center justify-center text-white font-semibold text-sm"
        >
          {{ userInitial }}
        </div>
        <div class="flex-1">
          <div class="relative">
            <textarea
              v-model="newComment"
              placeholder="写下你的评论..."
              class="w-full px-4 py-3 pr-12 border border-gray-300 dark:border-gray-600 rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-white dark:placeholder-gray-400"
              rows="3"
            ></textarea>
            <!-- 表情按钮 -->
            <button
              @click="toggleCommentEmoji"
              class="absolute right-3 top-3 w-6 h-6 flex items-center justify-center text-lg hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
              title="插入表情"
            >
              😊
            </button>
          </div>

          <!-- 评论表情选择器 -->
          <div
            v-if="showCommentEmoji"
            class="mt-2 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"
          >
            <div class="flex items-center gap-2 mb-2">
              <span class="text-xs text-gray-500 dark:text-gray-400">选择表情：</span>
            </div>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="emoji in quickEmojis"
                :key="emoji.emoji"
                @click="insertEmojiToComment(emoji.emoji)"
                class="w-8 h-8 flex items-center justify-center text-lg hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors duration-200 hover:scale-110"
                :title="emoji.label"
              >
                {{ emoji.emoji }}
              </button>
            </div>
          </div>

          <div class="flex justify-between items-center mt-2">
            <span class="text-sm text-gray-500 dark:text-gray-400">
              {{ newComment.length }}/500
            </span>
            <el-button
              type="primary"
              :disabled="!newComment.trim() || newComment.length > 500"
              @click="submitComment"
              class="bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 border-0"
            >
              发表评论
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list space-y-4">
      <div
        v-for="comment in displayComments"
        :key="comment.id"
        class="comment-item border-b border-gray-100 dark:border-gray-700 pb-4 last:border-b-0"
      >
        <div class="flex items-start gap-3">
          <div
            class="w-10 h-10 bg-gradient-to-br from-pink-400 to-red-500 rounded-full flex items-center justify-center text-white font-semibold text-sm"
          >
            {{ comment.author.charAt(0).toUpperCase() }}
          </div>
          <div class="flex-1">
            <div class="flex items-center gap-2 mb-2">
              <span class="font-medium text-gray-800 dark:text-white">{{ comment.author }}</span>
              <span class="text-sm text-gray-500 dark:text-gray-400">{{
                formatDate(comment.createTime)
              }}</span>
              <span
                v-if="comment.isAuthor"
                class="px-2 py-1 text-xs bg-blue-100 dark:bg-blue-900 text-blue-600 dark:text-blue-300 rounded-full"
              >
                作者
              </span>
            </div>
            <p class="text-gray-700 dark:text-gray-300 leading-relaxed mb-3">
              {{ comment.content }}
            </p>
            <div class="flex items-center gap-4 text-sm text-gray-500 dark:text-gray-400">
              <button
                @click="likeComment(comment.id)"
                class="flex items-center gap-1 hover:text-blue-500 dark:hover:text-blue-400 transition-colors"
                :class="{ 'text-blue-500 dark:text-blue-400': comment.isLiked }"
              >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path
                    v-if="comment.isLiked"
                    fill-rule="evenodd"
                    d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z"
                    clip-rule="evenodd"
                  />
                  <path
                    v-else
                    fill-rule="evenodd"
                    d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z"
                    clip-rule="evenodd"
                  />
                </svg>
                {{ comment.likes }}
              </button>
              <button
                @click="toggleReplyInput(comment.id)"
                class="flex items-center gap-1 hover:text-green-500 dark:hover:text-green-400 transition-colors"
              >
                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path
                    fill-rule="evenodd"
                    d="M7.707 3.293a1 1 0 010 1.414L5.414 7H11a7 7 0 017 7v2a1 1 0 11-2 0v-2a5 5 0 00-5-5H5.414l2.293 2.293a1 1 0 11-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z"
                    clip-rule="evenodd"
                  />
                </svg>
                {{ activeReplyId === comment.id ? '取消回复' : '回复' }}
              </button>
            </div>

            <!-- 回复输入框 -->
            <div v-if="activeReplyId === comment.id" class="mt-3 ml-6">
              <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-3">
                <!-- 微表情选择器 -->
                <div class="mb-3 pb-3 border-b border-gray-200 dark:border-gray-600">
                  <div class="flex items-center gap-2 mb-2">
                    <span class="text-xs text-gray-500 dark:text-gray-400">快速回复：</span>
                  </div>
                  <div class="flex flex-wrap gap-2">
                    <button
                      v-for="emoji in quickEmojis"
                      :key="emoji.emoji"
                      @click="quickReply(comment.id, emoji.emoji)"
                      class="w-8 h-8 flex items-center justify-center text-lg hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors duration-200 hover:scale-110"
                      :title="emoji.label"
                    >
                      {{ emoji.emoji }}
                    </button>
                  </div>
                </div>

                <div class="flex items-start gap-2">
                  <div
                    class="w-8 h-8 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-full flex items-center justify-center text-white font-semibold text-xs"
                  >
                    {{ userInitial }}
                  </div>
                  <div class="flex-1">
                    <div class="relative">
                      <textarea
                        v-model="replyContent"
                        :placeholder="`回复 ${comment.author}：`"
                        class="w-full px-3 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded-lg resize-none focus:ring-2 focus:ring-green-500 focus:border-transparent dark:bg-gray-600 dark:text-white dark:placeholder-gray-400 text-sm"
                        rows="2"
                      ></textarea>
                      <!-- 回复表情按钮 -->
                      <button
                        @click="toggleReplyEmoji(comment.id)"
                        class="absolute right-2 top-2 w-5 h-5 flex items-center justify-center text-sm hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
                        title="插入表情"
                      >
                        😊
                      </button>
                    </div>

                    <!-- 回复表情选择器 -->
                    <div
                      v-if="activeReplyEmojiId === comment.id"
                      class="mt-2 p-2 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600"
                    >
                      <div class="flex items-center gap-2 mb-2">
                        <span class="text-xs text-gray-500 dark:text-gray-400">选择表情：</span>
                      </div>
                      <div class="flex flex-wrap gap-1">
                        <button
                          v-for="emoji in quickEmojis"
                          :key="emoji.emoji"
                          @click="insertEmojiToReply(emoji.emoji)"
                          class="w-6 h-6 flex items-center justify-center text-sm hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors duration-200 hover:scale-110"
                          :title="emoji.label"
                        >
                          {{ emoji.emoji }}
                        </button>
                      </div>
                    </div>

                    <div class="flex justify-between items-center mt-2">
                      <span class="text-xs text-gray-500 dark:text-gray-400">
                        {{ replyContent.length }}/200
                      </span>
                      <div class="flex gap-2">
                        <el-button
                          size="small"
                          @click="cancelReply"
                          class="text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200"
                        >
                          取消
                        </el-button>
                        <el-button
                          type="success"
                          size="small"
                          :disabled="!replyContent.trim() || replyContent.length > 200"
                          @click="submitReply(comment.id)"
                          class="bg-gradient-to-r from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 border-0"
                        >
                          发表回复
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 回复列表 -->
            <div v-if="comment.replies && comment.replies.length > 0" class="mt-3 ml-6 space-y-3">
              <div
                v-for="reply in comment.replies"
                :key="reply.id"
                class="reply-item bg-gray-50 dark:bg-gray-700 rounded-lg p-3"
              >
                <div class="flex items-start gap-2">
                  <div
                    class="w-8 h-8 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-full flex items-center justify-center text-white font-semibold text-xs"
                  >
                    {{ reply.author.charAt(0).toUpperCase() }}
                  </div>
                  <div class="flex-1">
                    <div class="flex items-center gap-2 mb-1">
                      <span class="font-medium text-sm text-gray-800 dark:text-white">{{
                        reply.author
                      }}</span>
                      <span class="text-xs text-gray-500 dark:text-gray-400">{{
                        formatDate(reply.createTime)
                      }}</span>
                      <span class="text-xs text-gray-400 dark:text-gray-500">回复</span>
                      <span class="text-xs text-blue-600 dark:text-blue-400 font-medium">{{
                        comment.author
                      }}</span>
                    </div>
                    <p class="text-sm text-gray-700 dark:text-gray-300">{{ reply.content }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalPages > 1" class="mt-6 flex justify-center">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="totalComments"
        layout="prev, pager, next"
        @current-change="handlePageChange"
        background
        class="comment-pagination"
      />
    </div>

    <!-- 空状态 -->
    <div v-if="displayComments.length === 0" class="text-center py-8">
      <div class="w-16 h-16 mx-auto mb-4 text-gray-300 dark:text-gray-600">
        <svg fill="currentColor" viewBox="0 0 20 20">
          <path
            fill-rule="evenodd"
            d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7z"
            clip-rule="evenodd"
          />
        </svg>
      </div>
      <p class="text-gray-500 dark:text-gray-400">暂无评论，快来发表第一条评论吧！</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
// TODO: 导入评论API接口
// import { getComments, submitComment, likeComment, submitReply, type Comment, type CommentSubmitParams, type ReplySubmitParams } from '@/apis/blog/comment'

// 评论数据类型定义
interface Comment {
  id: number
  author: string
  content: string
  createTime: string
  likes: number
  isLiked: boolean
  isAuthor: boolean
  replies?: Reply[]
}

interface Reply {
  id: number
  author: string
  content: string
  createTime: string
  parentId: number
}

// Props
interface Props {
  articleId?: string | number
  articleTitle?: string
}

const props = withDefaults(defineProps<Props>(), {
  articleId: '',
  articleTitle: ''
})

// 响应式数据
const comments = ref<Comment[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const newComment = ref('')
const totalComments = ref(0)
const activeReplyId = ref<number | null>(null)
const replyContent = ref('')
const showCommentEmoji = ref(false) // 控制评论表情选择器显示
const activeReplyEmojiId = ref<number | null>(null) // 控制回复表情选择器显示

// 微表情数据
const quickEmojis = ref([
  { emoji: '👍', label: '点赞' },
  { emoji: '❤️', label: '爱心' },
  { emoji: '😊', label: '微笑' },
  { emoji: '🎉', label: '庆祝' },
  { emoji: '👏', label: '鼓掌' },
  { emoji: '💯', label: '满分' },
  { emoji: '🔥', label: '火' },
  { emoji: '✨', label: '闪光' },
  { emoji: '🙏', label: '感谢' },
  { emoji: '💪', label: '加油' }
])

// 计算属性
const totalPages = computed(() => Math.ceil(totalComments.value / pageSize.value))
const displayComments = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return comments.value.slice(start, end)
})

const userInitial = computed(() => {
  // TODO: 这里可以从用户信息中获取，暂时使用默认值
  return 'U'
})

// Mock数据生成 - 后续可以删除，替换为真实API调用
const generateMockComments = (): Comment[] => {
  const mockComments: Comment[] = []
  const authors = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']
  const contents = [
    '这篇文章写得很好，对我帮助很大！',
    '感谢分享，学到了很多新知识',
    '内容很实用，期待更多类似的文章',
    '这个观点很新颖，值得深入思考',
    '写得非常详细，感谢博主的分享',
    '这个技术点解释得很清楚',
    '学到了，谢谢分享经验',
    '内容质量很高，继续加油！'
  ]

  for (let i = 1; i <= 25; i++) {
    const comment: Comment = {
      id: i,
      author: authors[i % authors.length],
      content: contents[i % contents.length],
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      likes: Math.floor(Math.random() * 20),
      isLiked: Math.random() > 0.7,
      isAuthor: i === 1, // 第一个评论设为作者
      replies: []
    }

    // 随机添加回复
    if (Math.random() > 0.6) {
      const replyCount = Math.floor(Math.random() * 3) + 1
      for (let j = 1; j <= replyCount; j++) {
        const reply: Reply = {
          id: i * 100 + j,
          author: authors[(i + j) % authors.length],
          content: `回复${j}：${contents[(i + j) % contents.length]}`,
          createTime: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
          parentId: i
        }
        comment.replies!.push(reply)
      }
    }

    mockComments.push(comment)
  }

  return mockComments
}

// 方法
const formatDate = (dateString: string): string => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  if (newComment.value.length > 500) {
    ElMessage.warning('评论内容不能超过500字')
    return
  }

  try {
    // TODO: 调用后端接口提交评论
    // const response = await submitComment({
    //   articleId: Number(props.articleId),
    //   content: newComment.value
    // })

    // 模拟提交成功
    const newCommentObj: Comment = {
      id: Date.now(),
      author: '当前用户', // TODO: 这里应该从用户信息中获取
      content: newComment.value,
      createTime: new Date().toISOString(),
      likes: 0,
      isLiked: false,
      isAuthor: false,
      replies: []
    }

    comments.value.unshift(newCommentObj)
    totalComments.value++
    newComment.value = ''
    showCommentEmoji.value = false // 关闭表情选择器

    ElMessage.success('评论发表成功！')

    // 重置到第一页
    currentPage.value = 1
  } catch (error) {
    ElMessage.error('评论发表失败，请重试')
    console.error('提交评论失败:', error)
  }
}

const likeComment = async (commentId: number) => {
  try {
    // TODO: 调用后端接口点赞评论
    // const response = await likeComment({
    //   commentId,
    //   action: comment.isLiked ? 'unlike' : 'like'
    // })

    // 模拟点赞成功
    const comment = comments.value.find(c => c.id === commentId)
    if (comment) {
      if (comment.isLiked) {
        comment.likes--
        comment.isLiked = false
      } else {
        comment.likes++
        comment.isLiked = true
      }
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试')
    console.error('点赞失败:', error)
  }
}

// 回复相关方法
const toggleReplyInput = (commentId: number) => {
  if (activeReplyId.value === commentId) {
    // 如果当前评论的回复框已经打开，则关闭
    activeReplyId.value = null
    replyContent.value = ''
  } else {
    // 打开回复框，关闭其他回复框
    activeReplyId.value = commentId
    replyContent.value = ''
  }
}

const cancelReply = () => {
  activeReplyId.value = null
  replyContent.value = ''
  activeReplyEmojiId.value = null // 关闭表情选择器
}

// 快速表情回复
const quickReply = async (commentId: number, emoji: string) => {
  try {
    // TODO: 调用后端接口提交表情回复
    // const response = await submitReply({
    //   articleId: Number(props.articleId),
    //   parentId: commentId,
    //   content: emoji
    // })

    // 模拟提交成功
    const newReply: Reply = {
      id: Date.now(),
      author: '当前用户', // TODO: 这里应该从用户信息中获取
      content: emoji,
      createTime: new Date().toISOString(),
      parentId: commentId
    }

    // 找到对应的评论并添加回复
    const comment = comments.value.find(c => c.id === commentId)
    if (comment) {
      if (!comment.replies) {
        comment.replies = []
      }
      comment.replies.push(newReply)
    }

    // 关闭回复框
    activeReplyId.value = null

    ElMessage.success('表情回复发表成功！')
  } catch (error) {
    ElMessage.error('表情回复发表失败，请重试')
    console.error('提交表情回复失败:', error)
  }
}

const submitReply = async (commentId: number) => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }

  if (replyContent.value.length > 200) {
    ElMessage.warning('回复内容不能超过200字')
    return
  }

  try {
    // TODO: 调用后端接口提交回复
    // const response = await submitReply({
    //   articleId: Number(props.articleId),
    //   parentId: commentId,
    //   content: replyContent.value
    // })

    // 模拟提交成功
    const newReply: Reply = {
      id: Date.now(),
      author: '当前用户', // TODO: 这里应该从用户信息中获取
      content: replyContent.value,
      createTime: new Date().toISOString(),
      parentId: commentId
    }

    // 找到对应的评论并添加回复
    const comment = comments.value.find(c => c.id === commentId)
    if (comment) {
      if (!comment.replies) {
        comment.replies = []
      }
      comment.replies.push(newReply)
    }

    // 清空回复内容并关闭回复框
    replyContent.value = ''
    activeReplyId.value = null
    activeReplyEmojiId.value = null // 关闭表情选择器

    ElMessage.success('回复发表成功！')
  } catch (error) {
    ElMessage.error('回复发表失败，请重试')
    console.error('提交回复失败:', error)
  }
}

const handlePageChange = (page: number) => {
  currentPage.value = page
  // TODO: 可以在这里调用接口获取对应页的数据
  // loadComments()
}

// 加载评论列表
const loadComments = async () => {
  try {
    // TODO: 调用后端接口获取评论列表
    // const response = await getComments({
    //   articleId: Number(props.articleId),
    //   page: currentPage.value,
    //   pageSize: pageSize.value
    // })
    // comments.value = response.data.list
    // totalComments.value = response.data.total

    // 使用mock数据
    comments.value = generateMockComments()
    totalComments.value = comments.value.length
  } catch (error) {
    ElMessage.error('获取评论失败')
    console.error('获取评论失败:', error)
  }
}

// 表情选择器相关方法
const toggleCommentEmoji = () => {
  showCommentEmoji.value = !showCommentEmoji.value
}

const insertEmojiToComment = (emoji: string) => {
  newComment.value += emoji
  showCommentEmoji.value = false // 关闭表情选择器
}

const toggleReplyEmoji = (commentId: number) => {
  if (activeReplyEmojiId.value === commentId) {
    activeReplyEmojiId.value = null
  } else {
    activeReplyEmojiId.value = commentId
  }
}

const insertEmojiToReply = (emoji: string) => {
  replyContent.value += emoji
  activeReplyEmojiId.value = null
}

// 初始化
onMounted(async () => {
  await loadComments()
})
</script>

<style scoped>
.comment-section {
  transition: all 0.3s ease;
}

.comment-input textarea {
  transition: all 0.3s ease;
}

.comment-input textarea:focus {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.comment-item {
  transition: all 0.3s ease;
}

.comment-item:hover {
  transform: translateX(2px);
}

.reply-item {
  transition: all 0.3s ease;
}

.reply-item:hover {
  transform: translateX(2px);
}

/* 分页样式 */
:deep(.comment-pagination .el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #3b82f6;
}

:deep(.comment-pagination .el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #3b82f6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .comment-section {
    padding: 1rem;
  }

  .comment-input .flex {
    flex-direction: column;
    align-items: flex-start;
  }

  .comment-input .flex-1 {
    width: 100%;
    margin-top: 1rem;
  }
}
</style>
